<script setup lang="ts">
import { ref, reactive } from 'vue'
import ReDialog from '@/components/ReDialog/index.vue'
import { FormRules } from 'element-plus'
import { _addOperation, _updateOperation } from '@/api/auth'
import { Message } from '@/utils/message'
const emit = defineEmits(['afterSuccess'])

const dialogVisible = ref(false)
const title = ref('新增操作')
const formRef = ref()
const formState = ref({
  id: undefined,
  name: '',
  code: '',
  description: ''
})
const rules = reactive<FormRules>({
  name: [
    { required: true, message: '请输入操作名称', trigger: 'blur' },
    {
      min: 2,
      max: 16,
      message: '操作名称长度应在2到16个字符之间',
      trigger: 'blur'
    }
  ],
  code: [
    { required: true, message: '请输入操作编码', trigger: 'blur' },
    {
      min: 2,
      max: 16,
      message: '操作编码长度应在2到16个字符之间',
      trigger: 'blur'
    }
  ]
})

const show = data => {
  if (data?.id) {
    title.value = '编辑操作'
    const { id, name, code, description } = data
    formState.value = { id, name, code, description }
  } else {
    title.value = '新增操作'
  }
  dialogVisible.value = true
}
const handleClose = () => {
  dialogVisible.value = false
  formRef.value.clearValidate()
  formState.value = {
    id: undefined,
    name: '',
    code: '',
    description: ''
  }
}

const submit = () => {
  formRef.value.validate(valid => {
    if (valid) {
      const params = {
        ...formState.value
      }
      const func = title.value === '新增操作' ? _addOperation : _updateOperation
      func(params)
        .then(res => {
          Message.success(res.message)
          emit('afterSuccess')
          handleClose()
        })
        .catch(err => {
          Message.error(err.message)
        })
    }
  })
}
defineExpose({
  show
})
</script>

<template>
  <ReDialog
    v-model="dialogVisible"
    :title="title"
    @before-close="handleClose"
    @submit="submit"
  >
    <el-form
      ref="formRef"
      :model="formState"
      :rules="rules"
      label-position="right"
      label-width="80px"
    >
      <el-form-item label="操作编码" prop="code">
        <el-input
          v-model.trim="formState.code"
          placeholder="请输入操作编码"
          maxlength="16"
          show-word-limit
          clearable
        />
      </el-form-item>
      <el-form-item label="操作名称" prop="name">
        <el-input
          v-model.trim="formState.name"
          maxlength="16"
          show-word-limit
          placeholder="请输入操作名称"
          clearable
        />
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input
          v-model="formState.description"
          :rows="2"
          type="textarea"
          placeholder="请输入操作描述"
          maxlength="255"
          show-word-limit
          clearable
        />
      </el-form-item>
    </el-form>
  </ReDialog>
</template>
